import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;

// This is a servlet class that is being called, when user wants to subscribe.
public class User_subscribe extends HttpServlet{
protected void doPost(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
 response.setContentType("text/html");
 PrintWriter pw = response.getWriter();
 String applicationid = request.getParameter("applicationid");
 String applicationcredentials = request.getParameter("applicationcredentials");
 String login = request.getParameter("login");
 String credentials = request.getParameter("credentials");
 String first = request.getParameter("first");
 String last = request.getParameter("last");

 //connect to the database
 Connection con = null;
 ResultSet rs = null;
 Statement stmt = null;
 PreparedStatement pst = null;
 String query = "";
 try {
  Class.forName("com.mysql.jdbc.Driver").newInstance();
  con = DriverManager.getConnection("jdbc:mysql://bungle08.cs.toronto.edu:3306/group22",
   "group22", "123456");

  
   // check to susee if the user exists already (ie, userId exists)
   query = "SELECT id from user where id = \""+login+"\"";
   stmt = con.createStatement();  
   rs = stmt.executeQuery(query); 
   
   if(!rs.next()){   
    // If not, add the user to the database
    query = "INSERT INTO user (id, first_name, last_name, password) values (?,?,?,?)";  
    pst = con.prepareStatement(query);
    pst.setString(1,login);
    pst.setString(2,first);
    pst.setString(3,last);
    pst.setString(4,credentials);

    int i = pst.executeUpdate();
    if(i!=0){     } 
    String query2 = "insert into application (id, credential) values (?,?)";
    PreparedStatement pst2 = con.prepareStatement(query2);
    pst2.setString(1,applicationid);
    pst2.setString(2,applicationcredentials);
    int j = pst2.executeUpdate();
    if(j !=0 ){	}
    
   }
   // Return status back to the nanuk share server
   pw.println("{\"status\":200}");
 }
  catch(Exception e) {
  pw.println("Exception: " + e.getMessage());
 } finally {
  try {
   if(con != null)
    con.close();
  } catch(SQLException e) {}
 
 }
 
}
}
     
